<template>
    <div>
        <!--面包屑导航-->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!---->
        <el-card>
            <el-row :gutter="20">
                <el-col :span="8">
                    <el-input placeholder="请输入内容" class="input-with-select" v-model="queryInfo.query" clearable @clear="getUserList">
                        <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary" @click="dialogAddVisible = true">添加用户</el-button>
                </el-col>
            </el-row>
            <el-table :data="userList" style="width: 100%" border stripe>
                <el-table-column type="index"></el-table-column>
                <el-table-column prop="username" label="姓名"></el-table-column>
                <el-table-column prop="email" label="邮箱"></el-table-column>
                <el-table-column prop="mobile" label="电话"></el-table-column>
                <el-table-column prop="role_name" label="角色"></el-table-column>
                <el-table-column label="状态">
                    <template slot-scope="scope">
                        <el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row)"></el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="180px">
                    <template slot-scope="scope">
                        <el-button type="primary" icon="el-icon-edit" size="mini" @click="dialogEditShow(scope.row.id, scope.row.mg_state)"></el-button>
                        <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDelete(scope.row.id)"></el-button>
                        <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
                            <el-button type="warning" icon="el-icon-setting" size="mini" @click="dialogSetRoleShow(scope.row)"></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryInfo.pagenum" :page-sizes="[5, 10]"
    :page-size="queryInfo.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>
        </el-card>
        <el-dialog title="添加用户" :visible.sync="dialogAddVisible" @close="dialogAddClose">
            <el-form :model="newUser" :rules="newUserRules" ref="newUserRef" :label-width="formLabelWidth">
                <el-form-item label="用户名称" prop="username">
                    <el-input v-model="newUser.username"></el-input>
                </el-form-item>
                <el-form-item label="用户密码" prop="password">
                    <el-input v-model="newUser.password"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="newUser.email"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="mobile">
                    <el-input v-model="newUser.mobile"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogAddVisible = false">取 消</el-button>
                <el-button type="primary" @click="addUser">确 定</el-button>
            </div>
        </el-dialog>
        <el-dialog title="编辑用户信息" :visible.sync="dialogEditVisible" @close="dialogEditClose">
            <el-form :model="editUser" :rules="newUserRules" ref="editUserRef" :label-width="formLabelWidth">
                <el-form-item label="用户名称">
                    <el-input v-model="editUser.username" disabled></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="editUser.email"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="mobile">
                    <el-input v-model="editUser.mobile"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogEditVisible = false">取 消</el-button>
                <el-button type="primary" @click="handleEdit()">确 定</el-button>
            </div>
        </el-dialog>
        <!--分配角色弹窗-->
        <el-dialog title="分配角色" :visible.sync="dialogSetRoleVisible" @close="dialogSetRoleClose" width="50%">
            <div>
                <p>当前的用户：{{userInfo.username}}</p>
                <p>当前的角色：{{userInfo.role_name}}</p>
                <p>分配新角色：
                    <el-select v-model="newSetRole" placeholder="请选择">
                        <el-option v-for="item in roleList" :key="item.id" :label="item.roleName" :value="item.id">
                        </el-option>
                    </el-select>
                </p>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogSetRoleVisible = false">取 消</el-button>
                <el-button type="primary" @click="setRole">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data() {
        // 验证邮箱的规则
        var checkEmail = (rule, value, cb) => {
            // 验证邮箱的正则表达式
            const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
            if (regEmail.test(value)) {
                // 合法的邮箱
                return cb()
            }
            cb(new Error('请输入合法的邮箱'))
        }
        // 验证手机号的规则
        var checkMobile = (rule, value, cb) => {
            // 验证手机号的正则表达式
            const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
            if (regMobile.test(value)) {
                return cb()
            }
            cb(new Error('请输入合法的手机号'))
        }
        return {
            queryInfo: {
                query: '',
                pagenum: 1, // 当前的页数
                pagesize: 5// 当前每页显示多少条数据
            },
            userList: [],
            roleList: [],
            total: 0,
            newUser: {
               username: '',
               password: '',
               email: '',
               mobile: ''
            },
            editUser: {},
            newUserRules: {
                username: [
                    { required: true, message: '请输入用户名称', trigger: 'blur' },
                    { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入用户密码', trigger: 'blur' },
                    { min: 6, max: 15, message: '密码长度需在3到15个字符之间', trigger: 'blur' }
                ],
                email: [
                     { validator: checkEmail, trigger: 'blur' }
                ],
                mobile: [
                     { validator: checkMobile, trigger: 'blur' }
                ]
            },
            dialogAddVisible: false,
            dialogEditVisible: false,
            dialogSetRoleVisible: false,
            formLabelWidth: '100px',
            userInfo: {}, // 即将被分配角色的用户
            newSetRole: '' // 新分配的角色id
        }
    },
    created() {
        this.getUserList()
    },
    methods: {
        async getUserList() {
            const { data: res } = await this.$http.get('users', { params: this.queryInfo })
            if (res.meta.status !== 200) return this.$message.error('获取用户列表失败')
            this.userList = res.data.users
            this.total = res.data.total
        },
        handleSizeChange(newSize) { // 监听每页条数的改变
            this.queryInfo.pagesize = newSize
            this.getUserList()
        },
        handleCurrentChange(newPage) { // 监听页码值改变
            this.queryInfo.pagenum = newPage
            this.getUserList()
        },
        async userStateChange(userinfo) { // 监听switch状态的改变
            const { data: res } = await this.$http.put('users/' + userinfo.id + '/state/' + userinfo.mg_state)
            if (res.meta.status !== 200) {
                userinfo.mg_state = !userinfo.mg_state
                return this.$message.error(res.meta.msg)
            }
            this.$message.success(res.meta.msg)
            this.getUserList()
        },
        addUser() { // 添加用户
            this.$refs.newUserRef.validate(async valid => {
                if (!valid) return
                const { data: res } = await this.$http.post('users', this.newUser)
                if (res.meta.status !== 201) {
                    return this.$message.error(res.meta.msg)
                }
                this.$message.success(res.meta.msg)
                this.dialogAddVisible = false
                this.getUserList()
            })
        },
        async dialogEditShow(uId, type) { // 打开并查询用户
            this.dialogEditVisible = true
            const { data: res } = await this.$http.get('users/' + uId)
            if (res.meta.status !== 200) {
                return this.$message.error(res.meta.msg)
            }
            this.editUser = res.data
        },
        dialogAddClose() {
            this.$refs.newUserRef.resetFields()
        },
        dialogEditClose() {
            this.$refs.editUserRef.resetFields()
        },
        dialogSetRoleClose() {
            this.newSetRole = ''
            this.userInfo = {}
        },
        handleEdit() {
            this.$refs.editUserRef.validate(async valid => {
                if (!valid) return
                const { data: res } = await this.$http.put('users/' + this.editUser.id, { email: this.editUser.email, mobile: this.editUser.mobile })
                if (res.meta.status !== 200) {
                    return this.$message.error(res.meta.msg)
                }
                this.$message.success(res.meta.msg)
                this.dialogEditVisible = false
                this.getUserList()
            })
        },
        handleDelete(uid) { // 删除用户
            this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                const { data: res } = await this.$http.delete('users/' + uid)
                if (res.meta.status !== 200) {
                    return this.$message.error(res.meta.msg)
                }
                this.$message.success(res.meta.msg)
                this.getUserList()
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                })
            })
        },
        async dialogSetRoleShow(user) {
            this.userInfo = user
            // 获取所有角色列表
            const { data: res } = await this.$http.get('roles')
            if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
            this.roleList = res.data
            this.dialogSetRoleVisible = true
        },
        async setRole() {
            if (!this.newSetRole) {
                return this.$message.error('请选择要分配的角色！')
            }
            const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`, { rid: this.newSetRole })
            if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
            this.$message.success(res.meta.msg)
            this.dialogSetRoleVisible = false
            this.getUserList()
        }
    }
}
</script>

<style lang="less" scoped>

</style>